var cheerio = require('cheerio');
var fs = require('fs');
var lib = require('../../lib/index.js');
var config = require('./config.json');

// 1.创建数据链接
var connection = lib.connection_tradechina();
connection.on('error', function(err) {
    console.log('db error', err);
    if (err.code === 'PROTOCOL_CONNECTION_LOST') {
        connection = lib.connection_tradechina();
    } else {
        throw err;
    }
});

function saveConfig(isAutoSave) {
    if(isAutoSave){
        fs.writeFile('./config.json', JSON.stringify(config), function(err) {
            if (err) {
                console.log(err);
            }else{
                console.log('config save ok');
            }
        });
    }else{
        console.log('中止程序,准备重启');
        fs.writeFile('./config.json', JSON.stringify(config), function(err) {
            if (err) {
                console.log(err);
            }else{
                console.log('中止程序前配置文件保存成功');
                process.exit(0);//主动中止程序
            }
        });
    }
}

function getTableName() {
    return 'tradechina_supply';
}

getList();
async function getList(category) {
    // await lib.wait(1000);
    var list_url = 'https://buyercenter.tradechina.com/search.html?st=9&page='+config.page+'&limit=10'
    var result = await lib.myRequest(list_url,{
    }).catch(function (err) {
        console.log('列表请求出错');
        console.log(err);
        return false;
    });
    if(!result){
        saveConfig();
        return false;
    }

    var $ = cheerio.load(result);

    console.log('列表采集开始');
    console.log('time:'+lib.getTime());
    console.log('当前列表页:'+config.page);
    console.log('最大页数:'+$('.new-page-number .ft-left').text().trim());

    var promiseArr = [];
    $('.centerCon_proList .centerCon_item').each(function (index) {
        // if(index == 0){
            var title = $(this).find('.centerCon_item_titleLink').text().trim();
            var href = $(this).find('.centerCon_item_titleLink').attr('href');
            var promiseFun = new Promise((resolve, reject) => {
                setTimeout(function () {
                    var params = {
                        index:index,
                        title:title,
                        href:href,
                    };

                    getDetail(params,resolve,reject);
                }, config.detailTimeout*index);
            });

            promiseArr.push(promiseFun);
        // }
    });

    Promise.all(promiseArr).then((values) => {
        // console.log(values);
        // return false;
        var errorList = [];//是否重启
        for(var i=0;i<values.length;i++){
            var item = values[i];
            if(item.code == -1){
                errorList.push(item.href);
            }
        }

        // console.log(values);
        // console.log(errorList);
        // 重启
        if(errorList.length > values.length/2){
            console.log('出错信息太多');
            saveConfig();
            return false;
        }
        // return false;
        // 创建mdc supply表
        lib.creditTradechinaSupplyTable(connection,getTableName());
        for(var i=0;i<values.length;i++){
            var item = values[i];
            if(item.code == 200){
                console.log(item.index + ' ---- ok');

                // 插入数据
                lib.insertData(connection,getTableName(),item.data);
            }else{
                console.log(item.index + ' ---- err');
                console.log(item);
            }
        }
        // return false;

        // 当前下一页
        config.page++;
        saveConfig(true);
        // if(config.page > ){
        //     console.log();
        //     console.log();
        //     console.log('end');
        // }else{
            getList();
        // }
    }).catch((e)=>{
        console.log('promise.all Err');
        console.log(e);
    });
}

async function getDetail(obj,resolve,reject) {
    // 1.公司详情导航
    var result = await lib.myRequest('https://buyercenter.tradechina.com/'+obj.href).catch(function (err) {
        console.log('内容url请求出错:'+obj.href);
        // console.log(err);
        // saveConfig();
        return false;
    });
    if(!result){
        resolve({
            code:-1,
            index:obj.index,
        });
        return false;
    }
    var $ = cheerio.load(result);

    var siteId = $('#supplierInfoId').val();
    var supply = {
        title:obj.title
    };

    imgList = [];
    $('.img-list .list-ul li').each(function () {
        var src = $(this).find('img').attr('data-bigimg');
        imgList.push(src);
    });
    supply.imgList = JSON.stringify(imgList);

    var detail = [];
    $('.detail-block').each(function () {
        var blockTitle = $(this).find('.detail-title').text().trim();

        var content = {};
        $(this).find('.detail-content tr').each(function () {
            var key = $(this).find('td').eq(0).text().trim();
            var value = $(this).find('td').eq(1).text().trim();
            content[key] = value;
        });
        detail.push({
            key:blockTitle,
            value:content
        })
    });
    supply.detail = JSON.stringify(detail);

    // 基本信息
    var result2 = await lib.myRequest('https://buyercenter.tradechina.com/supplier/companyProfile.page',{
        method:'post',
        // headers:{
        //     'content-type':'application/x-www-form-urlencoded; charset=UTF-8'
        // },
        data:{
            sid:siteId
        }
    }).catch(function (err) {
        console.log('baseInfo url请求出错');
        // console.log(err);
        // saveConfig();
        return false;
    });
    if(!result2){
        resolve({
            code:-1,
            index:obj.index,
        });
        return false;
    }
    var $2 = cheerio.load(result2);
    var baseInfo = {};
    $2('.company-spec dl dt').each(function () {
        var key = $2(this).text().trim();
        var value = $2(this).next().text().trim();
        baseInfo[key] = value;
    });
    supply.baseInfo = JSON.stringify(baseInfo);
    supply.description = $2('.company-desc-text .company-info-detail').text().trim();

    resolve({
        code:200,
        index:obj.index,
        data:supply
    });
}
